package com.qqt.csr.common.acl.pconline;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qqt.csr.common.utils.HttpClientUtil;
import com.qqt.csr.common.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class PconlineServiceClient {
    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    /**
     * 获取ip所在地址
     *
     * @param ip
     * @return
     */
    public static String getRealAddressBy(String ip) {
        // 内网不查询
        if (IPUtil.isInnerIP(ip)) {
            return "内网IP";
        }
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("ip", ip);
            paramMap.put("json", "true");
            String respStr = HttpClientUtil.get(IP_URL, paramMap);
            if (StringUtils.isBlank(respStr)) {
                log.info("获取地理位置返回为空,ip:{}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSON.parseObject(respStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常,ip:{}", ip, e);
        }
        return UNKNOWN;
    }

}
